package top.jinlijun.heytea.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.jinlijun.heytea.entities.*;
import top.jinlijun.heytea.service.IOrderService;
import top.jinlijun.heytea.service.IStoreService;
import top.jinlijun.heytea.tools.CommodityTools;

import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CommodityTools tools;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IStoreService storeService;

    @RequestMapping("/addOrder")
    public RetResult addOrder(Order order, String commodityListJSON) {
        logger.info("添加商品");
        String orderId = tools.getUUID();
        List<Commodity> commodityList = JSON.parseArray(commodityListJSON, Commodity.class);
        order.setOrderId (orderId);
//        order.setCommodityList(commodityList);
        for (Commodity commodity : commodityList) {
            commodity.setOrderId(orderId);
            orderService.insertOrderCommodity(commodity);
        }
        orderService.insertOrder(order);
        System.out.println(order);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("/getCurrentOrders")
    public RetResult getCurrentOrders(Order order) {
        List<Order> orderList = orderService.getOrderByState(order);
        for (Order o : orderList) {
            List<Commodity> commodities = orderService.getCommodityByOrder(o);
            o.setCommodityList(commodities);
            o.setStore(storeService.getStoreById(o.getStoreId()));
        }
        return RetResponse.makeOKRsp(orderList);
    }

    @RequestMapping("/getHistoryOrders")
    public RetResult getHistoryOrders(Order order) {
        List<Order> orderList = orderService.getHistoryOrder(order);
        for (Order o : orderList) {
            List<Commodity> commodities = orderService.getCommodityByOrder(o);
            o.setCommodityList(commodities);
            o.setStore(storeService.getStoreById(o.getStoreId()));
        }
        return RetResponse.makeOKRsp(orderList);
    }

}
